package com.jwt.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RequestMapping
@RestController
public class CSController {
    @PostMapping("/login")
    public String login(String username, String password, HttpServletResponse response,HttpServletRequest request){
        if (username==null||password==null){
            return "账号或者密码为空";
        }
        if ("lcq".equals(username)&&"lcq".equals(password)){
            HttpSession session = request.getSession();
            //保存登录信息到session做在线校验
            session.setAttribute("user-info",username+password);
            //添加一个cookie，每次请求都在线的意思
            Cookie cookie = new Cookie("loginFlag","true");
            cookie.setMaxAge(7*24*60);
            cookie.setPath("/");
            response.addCookie(cookie);
            //存入浏览器的sessionId
            System.out.println("sessionId:"+request.getSession().getId());
            return "登录成功！！！";
        }
        return "账号或者密码错误！！！";
    }
    @GetMapping("/toList")
    public ModelAndView toList(ModelAndView modelAndView){
        modelAndView.setViewName("list");
        return modelAndView;
    }
    @GetMapping("/list")
    public String list(HttpServletRequest request){
        //存入浏览器的sessionId
        System.out.println("sessionId:"+request.getSession().getId());
        Cookie[] cookies = request.getCookies();
        String cookie="";
        for (int i = 0; i < cookies.length; i++) {
            cookie+="cookName:"+cookies[i].getName()+",value:"+cookies[i].getValue()+"<br/>";
        }
        return cookie;
    }
}
